<template>
  <div class="app-container">
    <div v-if="setPermissionBtn('/server/user/query', searchBtn)" class="inputBox">
      <el-input v-model="search.username" class="input" placeholder="请输入用户名称查询" />
      <el-select v-model="search.roleId" placeholder="请选择角色">
        <el-option v-for="(item, index) in role" :key="index" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="search.name" class="input" placeholder="请输入姓名查询" />
      <el-select v-model="search.status" class="teacherStatus" placeholder="请选择用户状态">
        <el-option label="停用" value="0" />
        <el-option label="启用" value="1" />
      </el-select>
      <el-button type="primary" class="ml10" @click="toSearch">{{ searchBtn.btnName }}</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
      <!-- <el-button v-show="permissionShow && permissionBoolean('新增')" type="primary" @click="addCourseType">新增</el-button> -->
    </div>
    <el-button v-if="setPermissionBtn('/server/user/add', addBtn)" type="primary" class="addBtn" @click="toaddPage()">{{ addBtn.btnName }}</el-button><br><br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <el-table-column label="用户名称">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="手机号">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间">
        <template slot-scope="scope">
          {{ scope.row.lastLoginTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ scope.row.availableStatus | typeStr }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="270">
        <template slot-scope="scope">
          <!-- <el-button
            v-show="permissionShow && permissionBoolean('查看')"
            size="mini"
            type="warning"
            @click="dialogDetail(scope.$index)">查看</el-button> -->
          <el-button
            v-if="setPermissionBtn('/server/user/info', scope.row)"
            size="mini"
            value="查看"
            type="warning"
            @click="dialogDetail(scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('edit', scope.row)"
            :disabled="scope.row.availableStatus === 1"
            size="mini"
            value="编辑"
            type="primary"
            @click="editRow(scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('enable/disable', scope.row)"
            :type="scope.row.availableStatus == 0?'success':'danger'"
            size="mini"
            value="启用/停用"
            @click="updateStatus(scope.row.id, scope.row.availableStatus)"
            v-html="splitName(scope.row.btnName, scope.row.availableStatus)"/>
            <!-- <el-button
            :type="scope.row.status == 0?'success':'danger'"
            size="mini"
            @click="enable(scope.row.id, scope.row.status)">{{ scope.row.status == 0 ? "启用" : "禁用" }}</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <detail :detialvisible.sync="dialogTableVisible" :dialogdata.sync="list" :myindex.sync="detailIndex" :detail-mode="'sysUser'" />
  </div>
</template>

<script>
import { getServerUserList, editServerUser, updateServerUser } from '@/api/sysUser'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import detail from '@/components/detail'
import { getRoleList } from '@/api/sysRole'
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { getPermission } from '@/api/permission'

export default {
  components: { Pagination, detail },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeStr(type) {
      const typesMap = {
        0: '禁用',
        1: '启用'
      }
      return typesMap[type]
    }
  },
  data() {
    return {
      searchBtn: {},
      list: [],
      role: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 0,
        pageSize: 10
      },
      search: {
        username: '',
        roleId: '',
        name: '',
        status: ''
      },
      isShowDel: false,
      dialogFormVisible: false,
      temp: {
        status: ''
      },
      courseTypeId: null,
      course: {
        name: '',
        introduce: '',
        price: '',
        imgUrl: ''
      },
      fileList: [],
      imgSrc: '',
      actionUrl: 'https://upload-z2.qiniup.com',
      isEdit: false,
      uploadData: {
        key: '',
        token: ''
      },
      dialogTableVisible: false,
      detailIndex: -1,
      permissionShow: false, // 权限数据未到达之前按钮隐藏
      permissionList: [], // 权限数据列表
      addBtn: {}
    }
  },
  computed: {
    startDate: function(e) {
      return new Date(this.startDate()).getTime()
    },
    // 权限按钮 computed
    setPermissionBtn() {
      return function(str, row) {
        let index = -1
        const buttonList = this.$store.getters.button
        index = buttonList.findIndex(item => item.value === str)
        // console.log(index)
        if (index !== -1) {
          row.btnName = buttonList[index].name
          return true
        } else {
          return false
        }
      }
    },
    // 用于 停用/启用  上架/下架 按钮的显示
    splitName() {
      return function(name, status) {
        const nameArr = name.split('/')
        if (status === 0) {
          return nameArr[0]
        } else {
          return nameArr[1]
        }
      }
    }
  },
  watch: {
    'permissionList'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  created() {
    this.fetchData()
    // 角色列表
    this.getRoleListFn()
  },
  mounted() {
    this.getPermissonFn() // 获取按钮权限 vuex的button
  },
  methods: {
    getRoleListFn() {
      getRoleList().then(response => {
        this.role = response.data.list
        console.log(this.role)
      })
    },
    toaddPage() {
      this.$router.push({
        path: '/basic/user/add'
      })
    },
    toReset() {
      this.search.username = ''
      this.search.roleId = ''
      this.search.name = ''
      this.search.status = ''
    },
    toSearch() {
      const newData = this.objectCon(this.listQuery, this.search)
      this.listLoading = true
      getServerUserList(newData).then(response => {
        console.log(response)
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    dateFormatStart: function(row, column) {
      const t = new Date(row.startDate);
      return t.getFullYear() + '-' + (t.getMonth() + 1) + '-' + t.getDate() + ' ' + t.getHours() + ':' + t.getMinutes() + ':' + t.getSeconds()
    },
    dateFormat: function(row, column) {
      const t = new Date(row.endDate);
      return t.getFullYear() + '-' + (t.getMonth() + 1) + '-' + t.getDate() + ' ' + t.getHours() + ':' + t.getMinutes() + ':' + t.getSeconds()
    },
    fetchData() {
      const newData = this.objectCon(this.listQuery)
      this.listLoading = true
      getServerUserList(newData).then(response => {
        console.log(response)
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    del(pid) {
      this.$confirm('确认要删除该咨询？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      }).catch(() => {
      })
    },
    dialogDetail(index) {
      console.log(index)
      this.dialogTableVisible = true
      this.detailIndex = index
    },
    edit(pid) {
      this.$router.push({
        path: '/vocational/courseAdd',
        query: {
          id: pid
        }
      })
    },
    addCourse(courseTypeId) {
      this.$data.courseTypeId = courseTypeId
      this.$data.dialogFormVisible = true
    },
    getValue(value) {
      this.$data.temp.status = value
    },
    getEnable(value) {
      this.$data.course.isEnable = value
    },
    getChildren(value) {
      this.$data.course.courseList = value
    },
    addCourseType() {
      this.$router.push({
        path: '/basic/user/add',
        query: { isEdit: false }
      })
    },
    editRow(pid) {
      const _this = this;
      const object = Object.assign({ isEdit: true }, _this.$data.list[pid])
      this.$router.push({
        path: '/basic/user/add',
        query: object
      })
    },
    // updateStatus(id, type) {
    //   const strAsk = type === 1 ? '是否停用？' : '是否启用？'
    //   const str = type === 0 ? '已停用' : '已启用'
    //   this.$confirm(strAsk, '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(res => {
    //     type === 0 ? type = 1 : type = 0
    //     const data = { status: type, id }
    //     batchStopAndEnable(data).then(res => {
    //       if (res.code === '200') {
    //         Message.success(str)
    //         this.fetchData()
    //       } else {
    //         Message.error(res.message + res.data)
    //       }
    //     })
    //   })
    // },

    updateStatus(id, status) {
      const strAsk = status === 1 ? '已停用' : '已启用'
      this.$confirm(status === 1 ? '是否停用？' : '是否启用？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        status === 1 ? status = 0 : status = 1
        updateServerUser({
          id: id,
          availableStatus: status
        }).then(res => {
          if (res.code === '200') {
            Message.success(strAsk)
            this.fetchData()
          } else {
            this.$message.error(res.data)
          }
        })
      }).catch(() => {
      })
    }
    // updateStatus(id, status) {
    //   this.$confirm(status === 1 ? '是否停用？' : '是否启用？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     editServerUser({
    //       id: id,
    //       status: status === 1 ? 0 : 1
    //     }).then(res => {
    //       if (parseInt(res.code) === 200) {
    //         this.fetchData()
    //       } else {
    //         this.$message.error(res.data)
    //       }
    //     })
    //   }).catch(() => {
    //   })
    // }
  }
}
</script>

<style>
  .el-icon-remove {
    margin-left: 10px;
  }
  .img_url {
    width: 110px;
    height: 110px;
  }
</style>
